package cn.kent.controller;

import cn.kent.config.RabbitConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/send")
    public void hello(String msg) {
        // 将来要发送的消息
        Message message = MessageBuilder.withBody(msg.getBytes()).build();
        // 发送消息，方法的返回值就是server 给出的响应
        Message result = rabbitTemplate.sendAndReceive(RabbitConfig.RPC_EXCHANGE, RabbitConfig.RPC_MSG_QUEUE, message);
        if (result != null) {
            // 发送的消息的 correlationId
            String correlationId = message.getMessageProperties().getCorrelationId();
            // 返回的消息的 correlationId
            String messageCorrelation = (String) result.getMessageProperties().getHeaders().get("spring_returned_message_correlation");
            if (correlationId.equals(messageCorrelation)) {
                System.out.println("收到的服务器响应为：" + new String(result.getBody()));
            }
        }


    }
}
